<template>
  <div v-if="config" class="m2o-field-setting">
    <div class="head">
      <div class="title">{{ $srv.getI18nByValue('字段配置') }}：</div>
      <Button size="small" type="primary" @click="selectFields">{{
        $srv.getI18nByValue('选择字段')
      }}</Button>
    </div>
    <div class="body" v-if="isShow">
      <Table
        highlight-row
        ref="currentRowTable"
        stripe
        border
        size="small"
        :columns="columns"
        :data="config"
      >
        <!-- <template #isShow="{ row, index }">
          <i-switch
            v-model="row.isShow"
            @on-change="isShowChange($event, row, index)"
          ></i-switch>
        </template> -->
        <template #lang="{ row }">
          <span>{{ $srv.getI18nBySrv(row.title) }}</span>
        </template>
        <!-- <template #filter="{ row }">
          <Input
            v-model="row.filtr"
            :placeholder="$srv.getI18nByValue('过滤值')"
          />
        </template>
        <template #order="{ row }">
          <Select
            clearable
            transfer
            v-model="row.sort.value"
            @on-change="saveChanges"
          >
            <Option value="desc">
              {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.desc') }}
            </Option>
            <Option value="asc">
              {{ $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.asc') }}
            </Option>
          </Select>
        </template> -->
      </Table>
    </div>
  </div>
</template>

<script lang="ts">
import { Tsrv } from '@/services';
import { Component, Model, Prop, Vue } from 'vue-property-decorator';

interface fieldConfig {
  title: string;
  isShow: boolean;
  // filter?: string | number;
  // sort?: any;
}

@Component
export default class oM2oFieldsSetting extends Vue {
  @Model('modelchange') config: Array<fieldConfig>;

  @Prop() m2oConfig: any;

  private sourceFields: Array<any> = [];

  private isShow: boolean = false;

  // eslint-disable-next-line no-template-curly-in-string
  private doubleQuotes = '${doubleQuotes}'; // 单引号占位符

  // eslint-disable-next-line no-template-curly-in-string
  private singleQuotes = '${singleQuotes}'; // 双相号占位符

  private columns: Array<any> = [
    // checkbox 选择框
    // {
    //   type: 'selection',
    //   width: 60,
    //   align: 'center'
    // },
    // index 序号
    {
      type: 'index',
      width: 60,
      align: 'center'
    },
    {
      title: Tsrv.getI18nByValue('字段'),
      key: 'title',
      align: 'center'
      // resizable: true
      // width: 100
    },
    {
      title: Tsrv.getI18nByValue('本地语言'),
      slot: 'lang',
      align: 'center'
      // resizable: true
      // width: 100
    }
    // 是否显示
    // {
    //   title: Tsrv.getI18nByValue('显示'),
    //   // key: 'isShow'
    //   slot: 'isShow'
    //   // width: 60
    // }
    // // 过滤条件
    // {
    //   title: Tsrv.getI18nByValue('过滤条件'),
    //   slot: 'filter',
    //   align: 'center'
    // },
    // 排序
    // {
    //   title: Tsrv.getI18nByValue('排序'),
    //   align: 'center',
    //   children: [
    //     {
    //       title: Tsrv.getI18nByValue('顺序'),
    //       slot: 'order',
    //       align: 'center'
    //     }
    //     // {
    //     //   title: Tsrv.getI18nByValue('权重'),
    //     //   slot: 'weight',
    //     //   align: 'center'
    //     // }
    //   ]
    // }
  ];

  get toTable() {
    return this.m2oConfig?.toTable ?? '';
  }

  beforeCreate() {}

  created() {
    this.checkConfig();
  }

  mounted() {}

  private checkConfig() {
    // this.config.forEach(el => {
    //   if (Tsrv.noValue(el['filter'])) {
    //     el['filter'] = '';
    //   }
    //   if (Tsrv.noValue(el['sort'])) {
    //     el['sort'] = {
    //       value: '',
    //       weight: 0
    //     };
    //   }
    // });
    // this.saveChanges();
    this.isShow = true;
  }

  private isShowChange(value: boolean, row: any, idx: number) {
    const find = this.config.find(el => el.title === row.title);
    find.isShow = value;
    this.saveChanges();
  }

  private selectFields() {
    this.getSourceFields()
      .then(r => {
        if (r && !Tsrv.noValue(this.sourceFields)) {
          const allFields = this.sourceFields.map(f => ({
            key: f.title,
            label: f.title
          }));
          const selectFields = this.config.map(f => f.title);
          const sourceFields = [];
          allFields.forEach(el => {
            if (!selectFields.includes(el.key)) {
              sourceFields.push(el);
            }
          });
          Tsrv.utils
            .createModal('o-transfer', {
              modalTitle: '选择字段',
              transferTitle: ['未选字段', '已选字段'],
              filterable: true,
              // data: sourceFields,
              data: allFields,
              targetKeys: selectFields
            })
            .then(data => {
              data && this.fieldChange(data, selectFields);
              this.saveChanges();
            });
        }
      })
      .catch(err => {});
  }

  public fieldChange(newArr: string[], oldArr: string[]) {
    const add: string[] = [];
    const del: string[] = [];
    newArr
      .filter(value => oldArr.indexOf(value) === -1)
      .forEach(el => {
        add.push(el);
      });
    add.length && this.fieldAdd(add);
    oldArr
      .filter(value => newArr.indexOf(value) === -1)
      .forEach(el => {
        del.push(el);
      });
    del.length && this.fieldDel(del);
    // 整理字段
  }

  private fieldAdd(adds: string[]) {
    adds.forEach(add => {
      const find = this.sourceFields.find(f => f.title === add);
      const field = {
        title: find.title,
        // isShow: find.isShow
        isShow: true
        // filter: find.initFilter,
        // sort: {
        //   value: find.sort.value,
        //   weight: find.sort.weight
        // }
      };
      this.config.push(field);
    });
  }

  private fieldDel(dels: string[]) {
    dels.forEach(add => {
      const idx = this.config.findIndex(f => f.title === add);
      this.config.splice(idx, 1);
    });
  }

  private getSourceFields() {
    return new Promise(resolve => {
      if (Tsrv.noValue(this.toTable)) {
        return;
      }
      const toTable = Tsrv.utils.clone(this.toTable, true);
      this.$store
        .dispatch('getLayoutConfigAsync', {
          funid: null,
          field: toTable,
          type: 'component'
        })
        .then(res => {
          if (res) {
            const config = res?.current?.config;
            if (!Tsrv.noValue(config)) {
              const tableColumns = [];
              if (
                res.current['name'] === 'BasePanel' &&
                Tsrv.utils.has(config, 'formPanels')
              ) {
                config['formPanels'].forEach(panel => {
                  const cfg = panel['content'];
                  tableColumns.push(...cfg.formColumns);
                });
              } else {
                tableColumns.push(...config.tableColumns);
              }
              const fields = tableColumns
                .map(col => {
                  return {
                    id: col.fieldID,
                    title: col.field,
                    isShow: col.isShow,
                    filter: col.initFilter,
                    sort: {
                      value: col.initSort,
                      weight: col.initSortWeight
                    }
                  };
                })
                .filter(el => {
                  return el['isShow'] === true;
                });
              this.sourceFields = fields;
            }
            resolve(true);
          } else {
            resolve(false);
          }
        });
    });
  }

  private saveChanges() {
    this.$emit('modelchange', this.config);
    this.$emit('on-change');
  }
}
</script>

<style scoped lang="scss">
.m2o-field-setting {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 0 0 15px;
  .head {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .title {
      // font-size: 11px;
      // font-weight: 700;
    }
  }
  .body {
    width: 100%;
  }
}
</style>
